package com.eshipenet.shipnet.edgeboxextbuilder

import play.api.libs.json.JsObject

import scala.util.Try

sealed trait EdgeBoxModelAction {
  val id: String
}

case class EdgeBoxModelInsert(id: String, after: EdgeBoxModel)                       extends EdgeBoxModelAction
case class EdgeBoxModelUpdate(id: String, before: EdgeBoxModel, after: EdgeBoxModel) extends EdgeBoxModelAction
case class EdgeBoxModelDelete(id: String, before: EdgeBoxModel)                      extends EdgeBoxModelAction

object EdgeBoxModelAction {

  private def wrapEdgeBoxModel(data: JsObject): EdgeBoxModel = {
    val id = (data \ "id").as[String]
    EdgeBoxModel(id = id, data = data)
  }

  def apply(act: DebeziumParser.Action): Try[EdgeBoxModelAction] = act match {
    case DebeziumParser.Insert(after, _) =>
      Try {
        val box = wrapEdgeBoxModel(after)
        EdgeBoxModelInsert(box.id, box)
      }
    case DebeziumParser.Update(before, after, _) =>
      Try {
        val boxBefore = wrapEdgeBoxModel(before)
        val boxAfter  = wrapEdgeBoxModel(after)
        EdgeBoxModelUpdate(boxAfter.id, boxBefore, boxAfter)
      }
    case DebeziumParser.Delete(before, _) =>
      Try {
        val box = wrapEdgeBoxModel(before)
        EdgeBoxModelDelete(box.id, box)
      }
  }

}
